/**
 * @Copyright:Copyright (c) 1992 - 2015
 * @Company: TengTong
 */
package com.tengtong.duang.commons.convert.support;

import com.tengtong.duang.commons.base.AssertUtils;
import com.tengtong.duang.commons.convert.ConditionalConverter;
import com.tengtong.duang.commons.convert.ConversionException;
import com.tengtong.duang.commons.utils.ReflectUtils;
import com.tengtong.duang.commons.utils.StringUtils;

/**
 * 字符串类型转换器，可以将下面的内容转为字符串：
 *  
 *  1) 日期类型
 *  
 * @author jai
 *
 */
public class StringToEnumConverter implements ConditionalConverter {
		
	/* (non-Javadoc)
	 * @see com.tengtong.duang.commons.convert.ConditionalConverter#matches(java.lang.Class, java.lang.Class)
	 */
	@Override
	public boolean matches(Class<?> sourceType, Class<?> targetType) {
		AssertUtils.notNull(sourceType, "sourceType 不能为 null.");
		AssertUtils.notNull(targetType, "targetType 不能为 null.");
		
		return (String.class.equals(sourceType) && targetType.isEnum());
	}

	/* (non-Javadoc)
	 * @see com.tengtong.duang.commons.convert.ConditionalConverter#convert(java.lang.Object, java.lang.Class)
	 */
	@Override
	public Object convert(Object source, Class<?> targetType) {
		if(source != null && targetType != null){
			String name = (String)source;
			if(StringUtils.notNullAndEmpty(name)){
				try {
					return ReflectUtils.getEnumBy(targetType, name.trim());
				}
				catch (Exception e) {
					throw new ConversionException(String.class, targetType, source, e);
				}
			}
		}
		
		return null;
	}

}
